import { storeBindingsBehavior } from "mobx-miniprogram-bindings";
import mall from "@src/store/mall";
import base from "@src/store/base";
import { getPreOrderMsgFun, freightFee, updatePreOrder, createOrder } from "@mall/api/order";
import { checkPwdInit, getBaseInfo } from "@src/api/member";
import {getGoodsAndShopJoinPayChannels} from "@src/api/mall/store";
import router from "@src/router";
import mallPayBehavior from "./mallPayBehavior";
import member from "@src/store/member";
import $math from "@src/common/math"
import dayjs from "dayjs";
import { getStoreDetail} from '@src/api/mall/store'

Component({
  behaviors: [storeBindingsBehavior, mallPayBehavior],
  storeBindings: [{
    store: member,
    fields: ['phone', 'isMember',],
    actions: ['getBaseInfo']
  }, {
    store: mall,
    fields: ['curLocation', 'userLocation','storeId'],
    actions: ['initLocation','goodsAndShopJoinPay']
  }, {
    store: base,
    fields: ['isiPhoneX', 'themeColor', 'themeTitleColor', 'barHeight']
  }],
  properties: {},
  data: {
    canPay: true,
    userPhone: null,
    arrivalTime: null,
    freightFee: 0,
    deliveryResult: { supply: true },
    totalFee: 0,
    count: 0,
    deliveryType: "",
    errorMsg: "",
    remark: "",
    discountInfo: null,
    pointsDiscount: null,
    address: null,
    normalAddress: null,
    preOrder: null,
    //是否同意预售条款
    agreePreSell: false,
    //预售信息对象
    goodsPresell: null,
    depositFee: 0,
    remaining: null,
    popTipStatus: false,//退出提示弹窗显示
    leaderCollect: null,//是否需要团长代收
    chakeLeaderCollect: null,
    groupInfo: null,//后端返回是否是团长，是否可以让团长代收
    payTime: null,
    dinnerList:{},
    dinnerOptions:{
      'EXPRESS':'直邮到家',
      'LOCAL':'送货上门',
      'SELF_PICKUP':'到店自提',
    },
    showDinner:false,
  },
  observers: {
    'groupInfo,leaderCollect': function (groupInfo, leaderCollect) {
      // wx.showModal({
      //   title: '温馨提示',
      //   content: `你参与的拼团购因为团长选择了代收方式，你选择的${'自提'}已被重置为与团长一致，点击确认继续下单`,
      //   cancelText: "返回", //默认是“取消”
      //   confirmText: "确认继续下单", //默认是“确定”
      //   success (res) {
      //     if (res.confirm) {
      //       console.log('用户点击确定')
      //     } else if (res.cancel) {
      //       console.log('用户点击取消')
      //     }
      //   }
      // })
      // wx.showModal({
      //   title: '温馨提示',
      //   content: `当前订单支持团长代收，请选择你的收货方式`,
      //   cancelText: "我自己收货", //默认是“取消”
      //   confirmText: "让团长帮我收货", //默认是“确定”
      //   success (res) {
      //     if (res.confirm) {
      //       console.log('用户点击确定')
      //     } else if (res.cancel) {
      //       console.log('用户点击取消')
      //     }
      //   }
      // })
      if (groupInfo && !groupInfo.isLeader && leaderCollect) {
        this.setData({ address: groupInfo.leaderDelivery, ['address.phone']: null });
      } else {
        this.setData({ address: this.data.normalAddress })
      }
    },
    'orderPayInfo,freightFee,pointsDiscount,discountInfo': function (orderPayInfo, freightFee, pointsDiscount, discountInfo) {
      if (!orderPayInfo) {
        return;
      }
      if (this.data.deliveryType === 'SELF_PICKUP') {
        freightFee = 0;
      }
      let totalFee = orderPayInfo.totalFee + freightFee;
      //各类优惠
      let activityDiscountsPrice = 0;
      if (orderPayInfo.activityDiscounts.length > 0) {
        orderPayInfo.activityDiscounts.forEach((item, index) => {
          activityDiscountsPrice += item.discountFee
        })
      }
      if (discountInfo) {
        totalFee = totalFee - discountInfo.discountFee;
      }
      if (pointsDiscount) {
        totalFee = totalFee - pointsDiscount.discountFee;
      }
      totalFee = totalFee - activityDiscountsPrice
      if (totalFee < 0) {
        totalFee = 0;
      }
      this.setData({ totalFee })
    },
    // 'phone': function (phone) {
    //   this.setData({ userPhone: phone })
    // },
    'preOrder': function (preOrder) {
      if (!preOrder) {
        return;
      }
      let allNum = 0;
      for (let i = 0; i < preOrder.items.length; i++) {
        allNum += preOrder.items[i].num
      }
      for (let i = 0; i < preOrder.invalidItems.length; i++) {
        allNum += preOrder.invalidItems[i].num
      }
      this.setData({ count: allNum })
    },
    'preOrder,deliveryResult': function (preOrder, deliveryResult) {
      let errorMsg = "", canPay = true;
      if (!preOrder) {
        this.setData({ errorMsg: '数据异常', canPay: false })
        return;
      }
      let delivery = preOrder.delivery;
      if (preOrder.errorCode !== 0) {
        canPay = false;
        errorMsg = preOrder.errorMsg;
      } else if (this.data.groupInfo && !this.data.groupInfo.isLeader && this.data.groupInfo.leaderCollect) {
        return;
      } else if (delivery.status !== 1) {
        canPay = false;
        if (delivery.deliveryType === 'EXPRESS') {
          errorMsg = "当前店铺不支持快递发货";
        } else if (delivery.deliveryType === 'LOCAL') {
          errorMsg = "当前店铺不支持到家配送";
        } else {
          errorMsg = "当前店铺不支持自取";
        }
      } else if (delivery.deliveryType !== 'SELF_PICKUP'
        && deliveryResult && !deliveryResult.supply) {
        canPay = false;
        if (deliveryResult.errorCode === 55005) {
          errorMsg = "地址超出了店铺的配送范围，请确认收货地址";
        } else {
          errorMsg = deliveryResult.errorMsg;
        }
      } else if (!this.data.address && (delivery.deliveryType === 'EXPRESS' || delivery.deliveryType === 'LOCAL')) {
        canPay = false;
        errorMsg = "请选择配送地址";
      }
      this.setData({ errorMsg, canPay })
    },
    // "deliveryType":function(value){
    //   if(value == 'thirdValue'){
    //       this.setDinner()
    //   }
    // }
  },
  methods: {
    onLoad: function (options) {
      console.log('options--', options)
      this.$pay = this.selectComponent("#pay");
      this.updateStoreBindings();
      let preNo = options.preNo;
      let snCode = options.snCode;
      let storeNo = options.storeNo;
      this.setData({ preNo: preNo, snCode: snCode, storeNo: storeNo })
      if (this.data.isMember === null) {
        this.getBaseInfo();
      }
      // this.setDinner()
      // const eventChannel = this.getOpenerEventChannel()
      // if (eventChannel && eventChannel.on) {
      //   eventChannel.on('showSelectDelivery', () => {
      //     this.selectComponent("#deliverySelect").open().then(res => {
      //       this.handleUpdatePreOrder({
      //         detail: { deliveryType: res }
      //       });
      //     });
      //   });
      // }
    },
    //接受是否需要团长代收
    handleLeaderCollect(e) {
      this.setData({ leaderCollect: e.detail });
      //触发团长代收状态重新给与快递费用查询
      // if(this.data.groupInfo.leaderDeliveryType!=="SELF_PICKUP"){
      this.fetchFreightFee();
      // }
    },

    fetchFreightFee() {
      if (this.data.preOrder.items.length === 0) {
        return;
      }

      let data = {
        storeId: this.data.preOrder.store.storeId,
        type: this.data.deliveryType,
        items: this.data.preOrder.items,
        deliveryInfo: this.data.address,
        source: { source: 0, preNo: this.data.preNo }
      }
      if (!data.deliveryInfo) return;
      console.log(this.data.address, "address")
      if (this.data.groupInfo) {
        if (this.data.leaderCollect && !this.data.groupInfo.isLeader) {
          data.deliveryInfo.leaderCollect = this.data.leaderCollect
        } else {
          if (data.deliveryInfo && data.deliveryInfo.leaderCollect) delete data.deliveryInfo.leaderCollect
        }
      }

      this.setData({ ['preOrder.items[0].discountSettings']: 1 })
      freightFee(data).then(res => {
        let result = res.data
        this.setData({ freightFee: result.freightFee, deliveryResult: result })
      })
    },
    showPriceChange() {
      wx.showModal({
        title: '温馨提示',
        content: "服务门店变更，订单商品的价格可能出现变化，请注意检查",
        confirmText: '好的',
        showCancel: false,
        success(res) {
          if (res.confirm) {
          }
        }
      })
    },
    showInvalidItems() {
      wx.showModal({
        title: '温馨提示',
        content: "服务门店变更，订单有部分商品缺货，请检查后再尝试提交订单",
        confirmText: '好的',
        showCancel: false,
        success(res) {
          if (res.confirm) {
          }
        }
      })
    },
    showPreSellDialog() {
      this.selectComponent("#saleDialog").open()
    },
    handleShowArrivalTime(e) {
      if (!e.detail) {
        this.selectComponent("#selectTime").open();
      } else {
        this.setData({ arrivalTime: null })
      }
    },
    handleUpdatePrepareTips(e) {
      this.setData({ prepareTips: e.detail })
    },
    handleUpdateRemark(e) {
      this.setData({ remark: e.detail })
    },
    handleUpdateDiscount(e) {
      this.setData({ discountInfo: e.detail, pointsDiscount: null })
    },
    handleUpdatePoints(e) {
      this.setData({ discountInfo: null, pointsDiscount: e.detail })
    },
    handleUpdateUserPhone(e) {
      this.setData({ userPhone: e.detail })
    },
    handleUpdateAddress(e) {
      console.info("handleUpdateAddress", e);
      let address = e.detail;
      if (!address) {
        this.setData({ address: null })
        return
      }
      this.setData({ userPhone: address.phone })
      this.setData({ normalAddress: address });
      if (this.data.groupInfo && !this.data.groupInfo.isLeader && this.data.leaderCollect) {
        this.setData({ address: this.data.groupInfo.leaderDelivery })
      } else {
        this.setData({ address: this.data.normalAddress })
      }
      this.fetchFreightFee();
    },
    handleUpdatePreOrder(e) {
      let store = e.detail.store;
      // let deliveryType = e.detail.deliveryType;
      let deliveryType = this.data.deliveryType;
      if (!store && !deliveryType) {
        return;
      }
      if (this.data.preOrder) {
        let originStore = this.data.preOrder.store;
        let originDeliveryType = this.data.deliveryType;
        if ((!store || store.storeId === originStore.storeId) && deliveryType === originDeliveryType) {
          // 没有修改
          return;
        }
      }
      let data = {
        preNo: this.data.preNo
      }
      if (store) {
        data['storeId'] = store.storeId;
      } else {
        data['storeId'] = this.data.preOrder.store.storeId;
      }
      // if (deliveryType) {
      //   data['deliveryType'] = deliveryType;
      // }
      this.selectComponent("#toast").show({ type: "loading" });
      updatePreOrder(data).then(res => {

        let orderPayInfo = this.data.preOrder.orderPayInfo;
        this.fetchData().then(() => {

          this.selectComponent("#toast").hide()
          let preOrder = this.data.preOrder;
          // 重置取货时间
          this.setData({ arrivalTime: null })
          if (preOrder.invalidItems.length > 0) {
            setTimeout(() => {
              this.showInvalidItems();
            }, 300)
          } else {
            if (orderPayInfo && preOrder.orderPayInfo.totalFee !== orderPayInfo.totalFee) {
              setTimeout(() => {
                this.showPriceChange();
              }, 300)
            }
          }
        })
      }).catch((e) => {
        this.selectComponent("#toast").hide()
      })
    },
    handleUpdateArrivalTime(e) {
      this.setData({ arrivalTime: e.detail })
    },

    phoneNumt(parame) {
      this.setData({ userPhone: parame.detail.userPhone })
    },
    checkOrderForm() {
      let deliveryType = this.data.deliveryType;
      //判断是否是团长代收
      if (this.data.groupInfo && !this.data.groupInfo.isLeader && this.data.leaderCollect) {
        return true
      }


      // 检查收货地址
      let address = this.data.address;
      if (!address && (deliveryType === 'EXPRESS' || deliveryType === 'LOCAL')) {
        wx.showToast({ title: '请选择收货地址', icon: 'none' })
        return false;
      }
      var myreg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
      if (!myreg.test(this.data.userPhone)) {
        wx.showToast({
          title: '' +
            '请输入正确手机号',
          icon: "none",
        })
        this.setData({ userPhone: "" });
        return false
      }
      //预售下单快递发货
      if (this.data.preOrder.presell && deliveryType === 'EXPRESS') {
        if (this.data.preOrder.delivery.prepareBeginTime) {
          let prepareBeginTime = this.data.preOrder.delivery.prepareBeginTime
          let now = dayjs()
          if (dayjs(prepareBeginTime).isBefore(now)) {
            this.data.arrivalTime = now.add(1, 'minutes').format('YYYY-MM-DD HH:mm')
          } else {
            this.data.arrivalTime = prepareBeginTime + " 00:00"
          }
        } else {
          this.data.arrivalTime = dayjs().add(this.data.preOrder.delivery.prepareTime, 'minutes').format('YYYY-MM-DD HH:mm')
        }
      }
      if (this.data.preOrder.delivery.limit === 2 && !this.data.arrivalTime) {
        wx.showToast({ title: '请选择' + (deliveryType === 'SELF_PICKUP' ? '自取' : '发货') + '时间', icon: 'none' })
        return false;
      }
      if (this.data.preOrder.presell && !this.data.agreePreSell) {
        wx.showToast({ title: '请同意商品预售条款', icon: 'none' });
        this.selectComponent("#saleDialog").open()
        return false;
      }
      return true;
    },

    // 获取商品购买的支付方式
    buyChannelsFun(){
      return new Promise(resolve => {
        let buyChannels = ''
        let idArr = []
        let goodsIdList = this.data.preOrder.items
        goodsIdList.forEach(el => {
          idArr.push(el.goodsId)
        })
        let parmData = {
          goodsIdList:idArr,
          storeId:this.data.preOrder.store.storeId,
        }
        getGoodsAndShopJoinPayChannels(parmData).then(res => {
          console.log('getGoodsAndShopJoinPayChannels',res)
          buyChannels = res.data
          resolve(buyChannels)
        })
      })
    },


    async handleToPay() {
	  const payCross = await this.goodsAndShopJoinPay(this.data.totalFee,this.data.preOrder.items,this.data.preOrder.store.storeId)
	  if(!payCross){
		return
	  }
      const { skipPwdAmount } = this.data.accountPayRule
      let isPwdInit = false
      const { data: { memberCategoryId } } = await getBaseInfo();
      if (memberCategoryId) {
        const { data: { initialed } } = await checkPwdInit();
        isPwdInit = initialed
      }
      if (memberCategoryId && this.data.totalFee > skipPwdAmount && !isPwdInit) {
        router.push({ name: "member/resetPassword", params: { type: "init" } })
        return
      }
      const payTime = this.data.payTime || 0
      if (new Date().getTime() - payTime < 2500) {
        return;
      } else {
        this.setData({ payTime: new Date().getTime() })
      }
      console.info("handleToPay")
      // 检查订单表单
      // wx.showLoading({ title: "加载中...", mark: true });
      if (!this.checkOrderForm()) {
        console.error("表单检验失败")
        return;
      }
      if (this.data.leaderCollect && !this.data.groupInfo.isLeader) {
        var myreg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
        if (!myreg.test(this.data.address && this.data.address.phone)) {
          wx.showToast({
            title: '' +
              '请输入正确预留手机号',
            icon: "none",
          })
          return false
        }
      }
      // 配送
      console.log(this.data.address)
      let deliveryInfo = JSON.parse(JSON.stringify(this.data.address));
      if (this.data.deliveryType === 'SELF_PICKUP') {
        if (this.data.leaderCollect && !this.data.groupInfo.isLeader) {
          deliveryInfo = {
            phone: this.data.address.phone
          }
        } else {
          deliveryInfo = {
            phone: this.data.userPhone,
          }
        }

      }
      if (this.data.preOrder.subType === 'GROUP') {
        if (this.data.groupInfo.isLeader) {
          deliveryInfo.leaderCollect = false
        } else {
          deliveryInfo.leaderCollect = this.data.leaderCollect
        }
      }

      if (this.data.groupInfo && !this.data.groupInfo.isLeader && this.data.leaderCollect && this.data.deliveryType !== this.data.groupInfo.leaderDeliveryType) this.setData({ deliveryType: this.data.groupInfo.leaderDeliveryType })

      deliveryInfo.arrivalTime = this.data.arrivalTime;
      let orderForm = {
        storeId: this.data.preOrder.store.storeId,
        type: this.data.deliveryType,
        items: this.data.preOrder.items,
        remark: this.data.remark,
        deliveryInfo: deliveryInfo,
        source: { source: 0, preNo: this.data.preNo },
        // subType: this.data.preOrder.presell ? 'PRESELL' : '',
        subType: this.data.preOrder.subType,
        storeNo: this.data.storeNo
      }
      if (this.data.preOrder.orderFrom && this.data.preOrder.orderFrom.activitySceneStr) {
        orderForm.source.activitySceneStr = this.data.preOrder.orderFrom.activitySceneStr
        orderForm.source.activityNo = this.data.preOrder.orderFrom.activityNo
        orderForm.activityType = this.data.preOrder.subType || null
        orderForm.items.forEach((item, index) => {
          item.activitySceneStr = this.data.preOrder.orderFrom.activitySceneStr
        })
      }
      // 优惠
      if (this.data.discountInfo) {
        orderForm['discountInfo'] = {
          'discountInfo': this.data.discountInfo
        }
      }
      if (this.data.pointsDiscount) {
        orderForm['discountInfo'] = {
          'pointsNum': this.data.pointsDiscount.num
        }
      }
      console.log('createOrder参数?>>>>',orderForm)
      const buyChannels = await this.buyChannelsFun()
      createOrder(orderForm).then(res => {
        // wx.hideLoading()
        if (res.code === 55308 || res.code === 55102) {
          this.setData({ popTipStatus: true })
          return;
        } else if (res.code !== 0) {
          this.selectComponent("#toast").show({ icon: "error", txt: res.msg, type: 'info', time: 2000 });
          return;
        }
        let orderNo = res.data.orderNo;
        let payFee = res.data.payFee;
        let depositOrderNo = res.data.depositOrderNo;
        let payChannels = [];
        // if (this.data.orderPayInfo.payChannels.indexOf("WX") !== -1) {
        //   payChannels.push("wx")
        // }
        // if (this.data.orderPayInfo.payChannels.indexOf("BALANCE") !== -1) {
        //   payChannels.push("balance")
        // }
        if (this.data.orderPayInfo.payChannels.indexOf("0") !== -1 && buyChannels.supplyWxPay) {
          payChannels.push("wx")
        }
        if (this.data.orderPayInfo.payChannels.indexOf("1") !== -1 && buyChannels.supplyBalance) {
          payChannels.push("balance")
        }
        let data = {
          orderNo: (this.data.preOrder.presell && this.data.goodsPresell.type === 'DEPOSIT') ? res.data.depositOrderNo : orderNo,
          payFee: payFee,
          payChannels: payChannels,
          hasDiscount: !!orderForm.discountInfo,
        }
        this.toMallPay(data).then(res => {
          console.info("成功", res)
          this.selectComponent("#toast").show({ icon: "", txt: "支付成功, 跳转中...", type: 'info', time: 2000 });
          setTimeout(() => {
            router.redirectTo({ name: 'mall/order-detail', params: { orderNo: orderNo } });
          }, 300)
        }).catch(res => {
          if (res && res.code === "cancel") {
            router.redirectTo({ name: 'mall/order-detail', params: { orderNo: orderNo } });
            return;
          }
          // 支付失败
          this.selectComponent("#toast").show({ icon: "error", txt: res.msg, type: 'info', time: 2000 });
          setTimeout(() => {
            router.redirectTo({ name: 'mall/order-detail', params: { orderNo: orderNo } });
          }, 1500)
        })
      }).catch((e) => {
        console.error(e)
        // wx.hideLoading();
        this.setData({ popTipStatus: true })
        this.selectComponent("#toast").show({ icon: "error", txt: "请求异常, 下单失败", type: 'info', time: 2000 });
      })
    },

    agreePreSellFunc() {
      this.setData({ agreePreSell: !this.data.agreePreSell })
    },
    submitPreSell() {
      console.log("接受i");
      this.setData({ agreePreSell: true })
    },
    handleReservedPhone(e) {
      // console.log(e.detail,)
      this.setData({ ['address.phone']: e.detail })
    },
    setDinner(){
      let {storeId} = this.data
      getStoreDetail({storeId}).then(res=>{
        if(res.code == 0){
          let {delivery} = res.data
          let dinnerType = ''
          if(delivery.supplyExpress){
            dinnerType = 'EXPRESS'
          }else if(delivery.supplyLocal){
            dinnerType = 'LOCAL'
          }else if(delivery.supplySelfPickup){
            dinnerType = 'SELF_PICKUP'
          }
          this.setData({dinnerList:delivery,deliveryType:dinnerType})
        }
      })
    },
    closeDinner(){
      this.setData({showDinner:false})
    },
    changeDinner(e){
      let {type} = e.currentTarget.dataset
      this.setData({deliveryType:type,'preOrder.delivery':type})
      this.closeDinner()
    }
  }
});
